package com.itheima.reggie.controller;

import com.itheima.reggie.common.ResultInfo;
import com.itheima.reggie.common.UserHolder;
import com.itheima.reggie.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;

// 前台用户
@RestController
public class UserController {

    @Autowired
    private UserService userService;

    @Autowired
    private RedisTemplate redisTemplate;

    // 发送短信
    @PostMapping("/user/sendMsg")
    public ResultInfo sendMsg(@RequestBody Map<String, String> param) {
        // 1.接收请求参数
        String phone = param.get("phone");
        // 2.调用service发短信
        userService.sendMsg(phone);
        // 3.返回结果
        return ResultInfo.success();
    }

    // 登录注册
    @PostMapping("/user/login")
    public ResultInfo login(@RequestBody Map<String, String> param) {
        // 1.接收请求参数
        String phone = param.get("phone");
        String code = param.get("code");
        // 2.调用service登录
        ResultInfo resultInfo = userService.login(phone, code);
        // 3.返回结果
        return resultInfo;
    }

    //退出登录
    @PostMapping("/user/logout")
    public ResultInfo logout() {

        //清除redis
        redisTemplate.delete("phone:"+ UserHolder.get().getPhone());

        //返回结果
        return ResultInfo.success();

    }

}
